﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Development.Network.AsycnSocket
{
    public class AsycnTokenManager
    {
        private readonly object _flagLock = new object();
        protected SortedDictionary<int, AsyncUserToken> m_manager = new SortedDictionary<int, AsyncUserToken>();
        protected Queue<AsyncUserToken> m_pool = new Queue<AsyncUserToken>();     //对象池

        /// <summary>
        /// 放入一个对象
        /// </summary>
        /// <param name="item"></param>
        public void Push(AsyncUserToken item)
        {
            if (item == null)
            {
                throw new ArgumentException("AsynObjectPool Items added  cannot be null");
            }
            lock (_flagLock)
            {
                m_pool.Enqueue(item);
                m_manager.Remove(item.LinkId);
            }
        }

        /// <summary>
        /// 获取一个对象
        /// </summary>
        /// <returns></returns>
        public AsyncUserToken Pop()
        {
            AsyncUserToken item = null;
            lock (_flagLock)
            {
                if (m_pool.Count != 0)
                {
                    item = m_pool.Dequeue();
                    m_manager.Add(item.LinkId, item);
                }
            }
            return item;
        }

        public List<AsyncUserToken> GetList()
        {
            lock (_flagLock)
            {
                return new List<AsyncUserToken>(m_manager.Values);
            }
        }

        public AsyncUserToken GetUserToken(int linkId)
        {
            AsyncUserToken token = null;
            lock(_flagLock)
            {
                m_manager.TryGetValue(linkId, out token);
            }
            return token;
        }

        public int Count()
        {
            lock(_flagLock)
            {
                return m_manager.Values.Count;
            }
        }


    }
}
